﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using HandyControl.Tools;
using OpenAiClient.Models;
using OpenAiClient.Repositories;
using OpenAiClient.Services;
using OpenAiClient.ViewModels;
using Prism.Events;

namespace OpenAiClient.Views
{
    /// <summary>
    /// SearchView.xaml 的交互逻辑
    /// </summary>
    // ReSharper disable once RedundantExtendsListEntry
    public partial class SearchView : UserControl
    {
        private readonly SearchViewModel _viewModel;

        public SearchView(
            IConfigService configService,
            IHttpService httpService,
            IStatisticsService statisticsService,
            IRepository<HistoryModel> historyRepository,
            IEventAggregator eventAggregator
        )
        {
            InitializeComponent();

            _viewModel = new SearchViewModel(
                configService,
                httpService,
                statisticsService,
                historyRepository,
                eventAggregator
            );

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                _viewModel.MessageSelected += OnMessageSelected;
                DataContext = _viewModel;
            }

            ListBoxChat.ItemContainerGenerator.ItemsChanged += ItemContainerGenerator_ItemsChanged;
        }

        private void ItemContainerGenerator_ItemsChanged(object sender, ItemsChangedEventArgs e)
        {
            var scrollViewer = VisualHelper.GetChild<ScrollViewer>(ListBoxChat);
            scrollViewer?.ScrollToBottom();
        }

        private void OnMessageSelected(FrameworkElement control)
        {
            if (FindResource("SelectMessageMenu") is ContextMenu contentMenu)
            {
                contentMenu.DataContext = _viewModel;
                contentMenu.PlacementTarget = control;
                contentMenu.IsOpen = true;
            }
        }
    }
}
